from numpy import arange, sin, pi, append, zeros, multiply
import subprocess
import matplotlib
import os.path
import os
from scipy.io import wavfile
matplotlib.use('WXAgg')
from fractions import Fraction

#Problematic dependencies
from scipy.sparse.csgraph import _validation
from scipy.io.matlab import streams

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

import wx

from importFiles import Import
from model import Model
from audioslice import AudioSlicing
from config import EffectsConfiguration
from sampleviewer import SampleViewer
from effects import Effects
from loopConfig import LoopConfiguration
from equaliser import Equaliser


class TransferAudio(wx.Dialog):

    def __init__(self, parent, id, model, path):
        wx.Dialog.__init__(self, parent, id, "Select Audio", size=(350, 300))
        self.parent = parent
        self.model = model
        self.path = path

        self.files = []

        sizer = wx.BoxSizer(wx.VERTICAL)

        self.audioFiles = wx.ListBox(self, 26, wx.DefaultPosition, (170, 130), [], wx.LB_SINGLE)

        remove = wx.Button(self, wx.ID_ANY, "Remove")
        remove.Bind(wx.EVT_BUTTON, self.removeFile)

        ok = wx.Button(self, wx.ID_ANY, "OK")
        ok.Bind(wx.EVT_BUTTON, self.transfer)

        sizer.Add(self.audioFiles)
        sizer.Add(remove)
        sizer.Add(ok)

        self.SetSizer(sizer)

    def removeFile(self, event):
        selections = list(self.audioFiles.GetSelections())
        self.audioFiles.Delete(selections[0])
        self.files.remove(selections[0])

    def transfer(self, event):
        self.model.transfer(self.path, self.files)
        self.Close()

    def update(self):
        self.audioFiles.Clear()
        self.files = self.model.getFiles()
        for item in self.model.getFiles():
            self.audioFiles.Insert(item, 0)


########################################################################
class Tabs(wx.Notebook):
    """
    Notebook class
    """

    #----------------------------------------------------------------------
    def __init__(self, parent, model):
        wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=
                             wx.BK_DEFAULT
                             #wx.BK_TOP 
                             #wx.BK_BOTTOM
                             #wx.BK_LEFT
                             #wx.BK_RIGHT
                             )

        # Create the first tab and add it to the notebook
        tabOne = Import(self, model)
        tabOne.update()
        self.AddPage(tabOne, "Import")


        # Create and add the second tab
        tabTwo = SampleViewer(self, model)
        self.AddPage(tabTwo, "Sample Viewer")

        # Create and add the third tab
        tabThree = AudioSlicing(self, model)
        self.AddPage(tabThree, "Audio Slicing")

        tabFour = Effects(self, model)
        self.AddPage(tabFour, "Effects")

        tabFive = EffectsConfiguration(self, model)
        self.AddPage(tabFive, "MPC Configuration")

        tabSeven = Equaliser(self, model)
        self.AddPage(tabSeven, "Equaliser")

        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)

    def OnPageChanged(self, event):
        old = event.GetOldSelection()
        new = event.GetSelection()
        sel = self.GetSelection()
        self.GetPage(new).update()
        event.Skip()

    def OnPageChanging(self, event):
        old = event.GetOldSelection()
        new = event.GetSelection()
        sel = self.GetSelection()
        event.Skip()


########################################################################
class Application(wx.Frame):
    """
    Frame that holds all other widgets
    """

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Application",
                          size=(800,700)
                          )
        panel = wx.Panel(self)

        menubar = wx.MenuBar()

        fileMenu = wx.Menu()
        transferMenu = wx.Menu()
        helpMenu = wx.Menu()

        quitItem = wx.MenuItem(fileMenu, 101, '&Quit\tCtrl+Q', 'Quit the Application')
        fileMenu.AppendItem(quitItem)
        wx.EVT_MENU(self, 101, self.OnQuit )

        usbItem = wx.MenuItem(transferMenu, 201, '&USB\tCtrl+U', 'Transfer via USB')
        transferMenu.AppendItem(usbItem)
        wx.EVT_MENU(self, 201, self.OnUSB )

        documentation = wx.MenuItem(helpMenu, 301, '&Documenation', 'Documentation')
        helpMenu.AppendItem(documentation)
        wx.EVT_MENU(self, 301, self.OnDocumentation )

        menubar.Append(fileMenu, '&File')
        menubar.Append(transferMenu, '&Transfer')
        menubar.Append(helpMenu, '&Help')

        self.model = Model()
        directory = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "../audio/"))
        for location in os.listdir(directory):
            self.model.addFile(os.path.normpath(os.path.join(directory, location)))
        notebook = Tabs(panel, self.model)
        sizer = wx.BoxSizer(wx.VERTICAL)
        #sizer.Add(menubar, 1, wx.ALL, 5)
        sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)
        self.SetMenuBar(menubar)
        self.Layout()

        self.Show()

    def OnDocumentation(self):
        return

    def OnQuit(self, event):
        self.Close()

    def OnUSB(self, event):
        dlg = wx.DirDialog(
            self, message="Choose a directory",
            style=wx.OPEN | wx.CHANGE_DIR
        )
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            print "Path: %s" % path
            self.model.TransferAudio(path)
            #dia = TransferAudio(self, wx.ID_ANY, self.model, path)
            #dia.update()
            #dia.ShowModal()
            #dia.Destroy()
            #self.model.transfer(path)

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = Application()
    app.MainLoop()
